package com.ymm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ymm.domain.entity.LoginUser;
import com.ymm.domain.entity.User;
import com.ymm.enums.AppHttpCodeEnum;
import com.ymm.enums.SystemContains;
import com.ymm.exception.SystemException;
import com.ymm.mapper.MenuMapper;
import com.ymm.mapper.UserMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(User::getUserName, username);
        queryWrapper.eq(User::getStatus, SystemContains.STATUS_NORMAL);
        User user = userMapper.selectOne(queryWrapper);
        if (Objects.isNull(user)) {
            throw new SystemException(AppHttpCodeEnum.USER_HAS_NOT_EXISTED);
        }
        // TODO:查询权限列表
        List<String> perms = menuMapper.getPermsById(user.getId());
        return new LoginUser(user,perms);
    }
}
